package com.dashu.authority.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dashu.authority.common.Constant;
import com.dashu.authority.entity.AuthenticationInfo;
import com.dashu.authority.entity.Menu;
import com.dashu.authority.entity.User;
import com.dashu.authority.exception.AuthorityException;
import com.dashu.authority.servie.AuthenticationInfoService;
import com.dashu.authority.servie.AuthorityOperateService;
import com.dashu.authority.servie.MenuService;
import com.dashu.authority.servie.RoleService;
import com.dashu.authority.servie.UserService;
import com.dashu.authority.util.AuthorityServiceUtil;
import com.dashu.authority.util.Competence;
import com.dashu.authority.util.ResultBean;
import com.dashu.authority.util.ReturnMessage;

@Controller
@RequestMapping("/competence")
public class CompetenceController extends BaseController {

	@Resource
	private AuthenticationInfoService infoService;
	@Resource
	private MenuService menuService;
	@Resource
	private AuthorityOperateService authorityService;
	@Resource
	private UserService userService;
	@Resource
	private	RoleService roleService;

	// 根据人员查询能查看的菜单
	@RequestMapping("/getMenuTreeByUser")
	public @ResponseBody Object getViewMenuCompetence(String DASHU_AUTH_TOKEN, Integer applicationId)
			throws AuthorityException {
		AuthorityServiceUtil.checkParam("用户token", DASHU_AUTH_TOKEN);
		AuthorityServiceUtil.checkParam("系统id", applicationId);
		AuthenticationInfo info = this.infoService.queryInfoByToken(DASHU_AUTH_TOKEN);// 查看token
		if (info == null) {
			throw new AuthorityException("2100002");
		}
		User user = userService.findAccountWithUserName(info.getLoginId());
		if (user == null) {
			throw new AuthorityException("2100002");
		}
		Map<Object, Object> paramsMap = new HashMap<Object, Object>();
		paramsMap.put("applicationId", applicationId);
		List<Menu> list =menuService.queryMenuTreeList(paramsMap);
		if (user.getIsSuperAdmin()) {// 如果是超级管理员 全部都给他
			String returnJson = ReturnMessage.getJsonString(this.setAdminAuthority(list));
			return returnJson;
		}
		Map<Integer, Long> auths = authorityService.getAuthorityByUserAndType(user.getId(),
				Constant.RESOURCES_TYPE_MENU,applicationId,null);
		if (list == null || list.size() == 0 || auths == null || auths.size() == 0) {
			String returnJson = ReturnMessage.getJsonString(new ArrayList<>());
			return returnJson;
		}
		List<Menu> menus = this.checkAuthority(list, auths);
		String returnJson = ReturnMessage.getJsonString(menus);
		return returnJson;
	}

	// 设置管理员权限
	private List<Menu> setAdminAuthority(List<Menu> list) {
		for (int i = 0; i < list.size(); i++) {
			Menu menu = list.get(i);
			menu.setAuthority(Competence.MAX_AUTHORITY);// 设置最大权重
			if (menu.getChildren() != null && menu.getChildren().size() > 0) {
				menu.setChildren(this.setAdminAuthority(menu.getChildren()));
			}
		}
		return list;
	}

	// 检查是否有权限
	private List<Menu> checkAuthority(List<Menu> list, Map<Integer, Long> auths) {
		List<Menu> ll = new ArrayList<Menu>();
		for (int i = 0; i < list.size(); i++) {
			Menu menu = list.get(i);
			Long l = auths.get(menu.getId());
			if (l != null && l != 0) {
				menu.setAuthority(l);
				if (menu.getChildren() != null && menu.getChildren().size() > 0) {
					menu.setChildren(this.checkAuthority(menu.getChildren(), auths));
				}
				ll.add(menu);
			}
		}
		return ll;
	}

	
	
	
	
	
	
	// 检查是否有分配权限
	private List<Menu> checkAssginAuthority(List<Menu> list, Map<Integer, Long> auths) {
		Competence c = new Competence();
		List<Menu> ll = new ArrayList<Menu>();
		for (int i = 0; i < list.size(); i++) {
			Menu menu = list.get(i);
			Long l = auths.get(menu.getId());
			if (l != null && l != 0 && c.checkProduct(l, 2)) {// 校验是否有分配的权限
				menu.setAuthority(l);
				if (menu.getChildren() != null && menu.getChildren().size() > 0) {
					menu.setChildren(this.checkAuthority(menu.getChildren(), auths));
				}
				menu.setAuthority(l);
				ll.add(menu);
			}
		}
		return ll;
	}
	
	// 检查被分配人的权限 标记菜单是否选中
	private List<Menu> checkSelectedAssginAuthority(List<Menu> list, Map<Integer, Long> auths) {
		for (int i = 0; i < list.size(); i++) {
			Menu menu = list.get(i);
			Long l = auths.get(menu.getId());
			if (l != null && l != 0) {// 校验是否有分配的权限
				menu.setAuthority(l);
				if (menu.getChildren() != null && menu.getChildren().size() > 0) {
					menu.setChildren(this.checkSelectedAssginAuthority(menu.getChildren(), auths));
				}
				menu.setChecked(true);
			}
		}
		return list;
	}

	// 返回管理员权限
	private List<Menu> getAdminAuthority(List<Menu> list,Map<Integer, Long> auths) {
		for (int i = 0; i < list.size(); i++) {
			Menu menu = list.get(i);
			menu.setAuthority(Competence.MAX_AUTHORITY);
			if (auths.get(menu.getId())!=null) {
				menu.setChecked(true);
				if (menu.getChildren() != null && menu.getChildren().size() > 0) {
					menu.setChildren(this.getAdminAuthority(menu.getChildren(),auths));
				}
			}
		}
		return list;
	}
	

	// 返回通用格式的权限
	private Map<String, Long> getEscapedAuthority(Map<Integer, Long> auths) {
		Map<String, Long> map= new HashMap<String, Long>();
		if (auths==null||auths.size()==0) {
			return map;
		}
		Set<Integer> set = auths.keySet();
		for (Integer i : set) {
			map.put(i.toString(), auths.get(i));
		}
		return map;
	}
	
	
	// 根据人员查询能分配权限的菜单
	@RequestMapping("/getMenuTreeAuthorityAssign")
	public @ResponseBody Object getMenuTreeAuthorityAssign(String DASHU_AUTH_TOKEN, Integer applicationId,
			String personnelType, Integer personnelId)
			throws AuthorityException {
		AuthorityServiceUtil.checkParam("用户token", DASHU_AUTH_TOKEN);
		AuthorityServiceUtil.checkParam("系统id", applicationId);
		AuthenticationInfo info = this.infoService.queryInfoByToken(DASHU_AUTH_TOKEN);// 查看token
		if (info == null) {
			throw new AuthorityException("2100002");
		}
		User user = userService.findAccountWithUserName(info.getLoginId());
		if (user == null) {
			throw new AuthorityException("2100002");
		}
		Map<Object, Object> paramsMap = new HashMap<Object, Object>();
		paramsMap.put("applicationId", applicationId);
		List<Menu> list = menuService.queryMenuTreeList(paramsMap);
		if (list == null || list.size() == 0 ) {//菜单为空 没法玩
			String returnJson = ReturnMessage.getJsonString(new ArrayList<>());
			return returnJson;
		}
		Map<Integer, Long> authority = authorityService.getAuthorityByUserAndResourcesType(personnelType,
				personnelId, Constant.RESOURCES_TYPE_MENU,applicationId);//获取被分配的个人权限		
		if (user.getIsSuperAdmin()) {// 如果是超级管理员 全部都给他
			list = this.getAdminAuthority(list, authority);
			Map<String, Long> au=this.getEscapedAuthority(authority);//把被分配人的权限也带回去
			String returnJson = ReturnMessage.getJsonString(list,au);
			return returnJson;
		}
		Map<Integer, Long> auths = authorityService.getAuthorityByUserAndType(user.getId(),
				Constant.RESOURCES_TYPE_MENU,applicationId,null);//获取分配人在某系统下的所有权限
		List<Menu> menus = this.checkAssginAuthority(list, auths);//根据分配人的权限决定菜单
		menus = this.checkSelectedAssginAuthority(menus, authority);//根据被分配的权限决定菜单是否要选中
		Map<String, Long> au=this.getEscapedAuthority(authority);//把被分配人的权限也带回去
		String returnJson = ReturnMessage.getJsonString(menus,au);
		return returnJson;
	}

	// 保存人员的菜单权限值
	@RequestMapping("/saveMenuAuthority")
	public @ResponseBody Object saveMenuAuthority(String personnelType, Integer personnelId,
			Integer applicationId, String value) throws AuthorityException {
		Map<String, Object> returnMap =authorityService.insertMenuAuthority(personnelType, personnelId, applicationId, value);
		return new ResultBean(returnMap).getResultMap();
	}
	
	

}
